#!/usr/bin/env python
import re
import subprocess
import time
import random

device_name="localhost:5555"
# ADB连接
def adb_connect():
    # 启动ADB连接
    adb_devices = subprocess.run(["adb", "devices"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if ":5555" not in adb_devices.stdout.decode() or "offline" in adb_devices.stdout.decode() :
        adb_disconnect = subprocess.run(["adb", "disconnect" ], stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        adb_tcpip_5555 = subprocess.run(["adb", "tcpip", "5555" ], stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        adb_tcpip = subprocess.run(["adb", "forward", "tcp:5555", "tcp:5555"], stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        if "refused" in adb_tcpip.stderr.decode():
            print("未连接设备")
            exit(0)
        adb_connect = subprocess.run(["adb", "connect", device_name], stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
        if "error" in adb_connect.stdout.decode() or "cannot" in adb_connect.stdout.decode():
            print("adb", "connect", device_name, "出错")
            exit(0)
    else:
        print (adb_devices)

# 启动微信界面
def start_app():
    if is_acitvity_we_wanted()==0:
        runresult=subprocess.run(["adb", "-s", device_name, "shell", "am", "start", "com.tencent.mm/.ui.LauncherUI"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        time.sleep(2)
        if "not found" in runresult.stdout.decode() or "not found" in runresult.stderr.decode():
            print("启动应用不成功")
            exit(0)

# 是否是微信运动排行榜界面
def is_acitvity_we_wanted():
    current_activity = subprocess.check_output(["adb", "-s", device_name, "shell", "dumpsys", "window", "|", "grep", "mCurrentFocus"]).decode("utf-8")
    return "plugin.exdevice.ui.ExdeviceRankInfoUI" in current_activity

# 获取界面截图并pull到本地
def pull_screen_ui(ui_path):
    if is_acitvity_we_wanted() == 1:
        # 获取当前界面的ui.xml
        uiResult=subprocess.run(["adb", "-s", device_name, "shell", "uiautomator", "dump", ui_path],
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if "ERROR:"  in uiResult.stderr.decode():
            print("uiautomator 出错，请重启手机,程序终止",uiResult.stderr.decode())
            exit(0)
        else:
            subprocess.run(["adb", "-s", device_name, "pull", ui_path], stdout=subprocess.DEVNULL,
                       stderr=subprocess.DEVNULL)

# 读取并点击UI中的点赞按钮
def read_xml_and_click(ui_name,keyword):
    with open(ui_name, 'r', encoding='utf-8') as file:
        text = file.read()

    array_x = []
    array_y = []

    # 使用正则表达式来匹配 "更多" 后面的 "bounds" 值
    pattern = keyword+r'.*?bounds="(\[\d+,\d+\]\[\d+,\d+\])"'
    boundsMatches = re.findall(pattern, text)

    # 提取匹配到的 "bounds" 值
    for bounds in  boundsMatches:
        # 使用正则表达式来匹配坐标值
        pattern = r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]'
        matchesPos = re.match(pattern, bounds)

        if matchesPos:
            x1, y1, x2, y2 = map(int, matchesPos.groups())

            x_point = round((x1 + x2) / 2 +random.randint(0, 4))
            y_point = round((y1 + y2) / 2 +random.randint(0, 4))
            if(x_point>400):
                array_x.append(x_point)
                array_y.append(y_point)
                print(f'x_point: {x_point}, y_point: {y_point}')
        else:
            print("未找到匹配的 bounds 值")



    for i in range( 0,len(array_x) , 1):
        x = array_x[i]
        y = array_y[i]
        print(f'开始点击红心按钮: {x},  {y}')
        subprocess.run(["adb", "-s", device_name, "shell", "input", "tap", str(x), str(y)])
        time.sleep(0.1)


        if is_acitvity_we_wanted()==0:
            subprocess.run(["adb", "-s", device_name, "shell", "input", "keyevent", "BACK"])
            time.sleep(1)
            if is_acitvity_we_wanted() == 0:
                subprocess.run(["adb", "-s", device_name, "shell", "input", "keyevent", "BACK"])
                time.sleep(1)
            dis = 120 * i + 360
            subprocess.run(["adb", "-s", device_name, "shell", "input", "swipe", "300", str(dis), "310", "200"])
            time.sleep(2)

    subprocess.run(["adb", "-s",device_name , "shell", "input", "swipe", "300", "1300", "310", "300"])
    time.sleep(2)

# 主程序
def main():
    adb_connect()
    start_app()
    checktime = 0
    while True:
        if is_acitvity_we_wanted():
            print("当前窗口为微信运动->步数排行榜")
            pull_screen_ui("/sdcard/ui.xml")
            read_xml_and_click("ui.xml",'com.tencent.mm:id/dj2')
        else:
            print("请先进入微信运动步数排行榜再运行该程序"+ checktime)
            time.sleep(2)
            checktime=checktime+1
            if checktime >10 :
                break


if __name__ == "__main__":
    main()